package com.newangels.action;

import com.newangels.util.startAgent;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * 启动Agent
 *
 * @author: TangLiang
 * @date: 2020/5/17 17:15
 * @since: 1.0
 */
@WebServlet("/startAgent")
public class StartAgentServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(StartAgentServlet.class.getName());

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        String[] agentList = request.getParameterValues("AGENT_LIST");
        //从 AGENT_LIST 获取需要的数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        try {
            for (String s : agentList) {
                String[] args = StringUtils.split(s, ",", 3);
                startAgent.main(args);
            }
        } catch (RuntimeException e) {
            logger.warning("Agent start failed\n" + e.getMessage());
            e.printStackTrace();
            jsonObject.put("success", false);
        }
        response.getWriter().write(jsonObject.toString());
    }

}
